package com.hk.core.web.client;

import com.hk.commons.util.SpringContextHolder;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestClient;

import java.util.Map;
import java.util.Objects;


/**
 * 比 {@link  org.springframework.web.client.RestTemplate} 更推荐使用的调用方式
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class RestClients {

    private static RestClient restClient;

    private static RestClient getRestClient() {
        if (Objects.isNull(RestClients.restClient)) {
            restClient = SpringContextHolder.getBean(RestClient.class);
        }
        return RestClients.restClient;
    }

    /**
     * http get request
     */
    public static <T> T get(String url, Map<String, ?> params, HttpHeaders headers, Class<T> responseType) {
        var client = getRestClient();
        return client.get()
                .uri(url, params)
                .headers(header -> {

                    if (Objects.nonNull(headers)) {
                        headers.forEach(header::addAll);
                    }
                })
                .retrieve()
                .body(responseType);
    }


    /**
     * http post request
     */
    public static <T> T post(String url, Map<String, ?> params, Object body, HttpHeaders headers, Class<T> responseType) {
        var client = getRestClient();
        return client.post()
                .uri(url, params)
                .contentType(MediaType.APPLICATION_JSON)
                .headers(header -> {
                    if (Objects.nonNull(headers)) {
                        headers.forEach(header::addAll);
                    }
                })
                .body(body)
                .retrieve()
                .body(responseType);
    }
}
